﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using IndyMosaic.Models.Web;
using IndyMosaic.Core.Extensions;
using System.IO;

namespace IndyMosaic.Org.Site.Controllers
{
    public class BinaryResourceController : Controller
    {
        BinaryResourceRepository repository = new BinaryResourceRepository();        

        public ActionResult Index()
        {
            return View(repository.GetAll());
        }
        public ActionResult Delete(Guid id)
        {
            repository.Delete(id);
            repository.Save();
            return View("Index", repository.GetAll());
        }
        [HttpPost]
        public ActionResult Upload(FormCollection forms)
        {
            foreach (HttpPostedFileBase file in Request.Files)
            {
                return AjaxUpload(file);
            }
            
            return View();
        }

        public FileUploadJsonResult AjaxUpload(HttpPostedFileBase file)
        {
            byte[] buf = new byte[file.ContentLength];
            file.InputStream.Read(buf, 0, file.ContentLength);

            BinaryResource br = new BinaryResource();
            br.ContentType = file.ContentType;
            br.FileName = file.FileName;
            br.Binary = buf;
            repository.Create(br);
            repository.Save();
            // Create URL for httphandler
            string url = string.Format("{0}?id={1}", Url.Content("~/getImage.axd"), br.ID.ToString());
            return new FileUploadJsonResult { Data = new { URL = url, Type = br.ContentType, FileName = br.FileName, RelativeUrl = Url.GetRelativeUrl(url) } };

        }

        

    }

    public class FileUploadJsonResult : JsonResult
    {
        public override void ExecuteResult(ControllerContext context)
        {
            this.ContentType = "text/html";
            context.HttpContext.Response.Write("<textarea>");
            base.ExecuteResult(context);
            context.HttpContext.Response.Write("</textarea>");
        }
    }
}
